package com.example.loginpage

import android.content.pm.PackageManager
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.loginpage.InputUtil.BitmapStorage
import com.example.loginpage.databinding.FragmentImageBinding

class ImageFragment : Fragment() {
    private lateinit var binding: FragmentImageBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentImageBinding.inflate(layoutInflater,container, false)

        context?.let { it1 ->
            val writePermissionGranted = ContextCompat.checkSelfPermission(it1, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED
            val readPermissionGranted = ContextCompat.checkSelfPermission(it1, "android.permission.READ_MEDIA_IMAGES") != PackageManager.PERMISSION_GRANTED
            if (writePermissionGranted && readPermissionGranted) {
                // 两个权限都没有被授予
                Toast.makeText(requireContext(), "请授予有关权限", Toast.LENGTH_SHORT).show()
                val permissions = arrayOf("android.permission.READ_MEDIA_IMAGES", "android.permission.READ_EXTERNAL_STORAGE")
                Toast.makeText(requireContext(), "请授予有关权限", Toast.LENGTH_SHORT).show()
                activity?.let { it2 -> ActivityCompat.requestPermissions(it2, permissions,
                    ChatFragment.PERMISSION_REQUEST_CODE
                ) }
            } else{
                val imageData = arguments?.getString("imageData")
                val bitmap = imageData?.let { BitmapStorage.readPicture(it) }
                binding.imageView.setImageBitmap(bitmap)
            }
        }
        return binding.root
    }
}